<?php
/**
 * Created by PhpStorm.
 * User: liuxiu
 * Date: 2022/7/14
 * Time: 18:32
 */

namespace business\elasticsearch\services;


use business\base\services\HighFrequencyWordService;
use business\elasticsearch\models\BigDataDeveloperModel;
use business\elasticsearch\models\BigDataRecommendedDeveloperModel;
use yii\elasticsearch\Command;

class BigDataDeveloperService
{
    /**
     * 开发商名称联想
     * @param $keyword
     * @param $pageSize
     * @return array
     */
    public function guessNames($keyword, $pageSize)
    {
        $page = 1;
        $condition = $this->constructCondition($keyword);
        $query = BigDataDeveloperModel::find()
            ->query($condition);
        //高亮处理
        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields" => [
                "developer_name" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['_score' => SORT_DESC]);

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $data = $query->asArray()->all();
        //数据处理
        $result = [];
        foreach ($data as $dv) {
            $item = array();
            $tmp = $dv['_source'];
            $tmp['nameSuggest'] = $tmp['developer_name'];
            if (!empty($dv['highlight'])) {
                foreach ($dv['highlight'] as $key => $value) {
                    $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                }
            }
            $item['developer_name'] = $tmp['developer_name'];
            $item['developer_nameHL'] = $tmp['developer_nameHL'];

            $result[] = $item;
        }
        return $result;
    }

    private function getAnalyze($keyword)
    {
        $esCommand = new Command();
        $esCommand->db = \Yii::$app->get('elasticsearch');
        $esCommand->index = BigDataDeveloperModel::index();
        $esCommand->type = BigDataDeveloperModel::type();
        $condition = [
            'text' => $keyword,
            "analyzer" => 'ik_smart'
        ];
        $urls = [];
        $urls[] = BigDataDeveloperModel::index();
        $urls[] = '_analyze';
        $str = json_encode($condition, JSON_UNESCAPED_UNICODE);
        $analyzeList = $esCommand->db->get($urls, [], $str);

        $subWords = [];
        if (!empty($analyzeList) && !empty($analyzeList['tokens'])) {
            $highFreWordService = new HighFrequencyWordService();
            $list = $highFreWordService->getList();
            foreach ($analyzeList['tokens'] as $key => $token) {
//                if (mb_strlen($token) == 1) {
//                    continue;
//                }
                if (!in_array($token['token'], $list)) {
                    $subWords[] = $token['token'];
                }
            }
        }
        return $subWords;
    }

    public function getDataList($keyword, $area, $province, $city, $companyType,
                                $projectType, array $landType, $tags, $companyLevel, $industryCategoryMiddle = [], $subscription = [], $page, $pageSize)
    {
        $condition = $this->constructCondition($keyword, $area, $province, $city, $companyType, $projectType, $landType, $tags, $companyLevel, $industryCategoryMiddle);
        $query = BigDataDeveloperModel::find()
            ->query($condition);
        //高亮处理
        $highlight = [
            'pre_tags' => ['<em class="_high">'],
            'post_tags' => ['</em>'],
            "fields" => [
                "developer_name" => new \stdClass(),
            ]
        ];
        $query->highlight($highlight);
        $query->orderBy(['_score' => SORT_DESC]);

        $total = $query->count();

        //分页处理
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $data = $query->asArray()->all();

        //数据处理
        $result = ['total' => $total, 'list' => []];
        foreach ($data as $dv) {
            $tmp = $dv['_source'];
            $tmp['nameSuggest'] = $tmp['developer_name'];
            if (!empty($dv['highlight'])) {
                foreach ($dv['highlight'] as $key => $value) {
                    $tmp[$key . 'HL'] = isset($value[0]) ? $value[0] : '';
                }
            }
            //https://img2.b2bmir.com/company/K003320.200x100.jpg?v=53f6b6312ee42f7bb68b8e34
//            if (!empty($tmp['developer_id']) && $tmp['developer_logo']) {
//                if (strtoupper(substr($tmp['developer_id'], 0, 1)) == 'K') {
//                    $tmp['developer_logo'] = \Yii::$app->params['ImgDomain'] . '/company/' . $tmp['developer_id'] . '.200x100.jpg?v=' . $tmp['developer_logo'];
//                }
//            }
            $tmp['_score'] = $dv['_score'];

            $developerScoreInfo = $this->getDeveloperScoreInfo($tmp, $subscription);
            $tmp['developer_score'] = $developerScoreInfo['developer_score'] ? intval($developerScoreInfo['developer_score']) : 0;

            $tmp = $this->formatDeveloper($tmp);
            $result['list'][] = $tmp;
        }
        return $result;
    }

    // 获取开发商评分(好客户模型评分)
    private function getDeveloperScoreInfo($data, $subscription)
    {
        $landDataArr = $data['land_data_arr'] ?? [];
        $projectDataArr = $data['project_data_arr'] ?? [];
        $subscriptionLandUsageList = $subscription['land_usage_list'] ?? [];
        $subscriptionProjectTypeList = $subscription['project_type_list'] ?? [];

        $investModuleScore = $data['invest_module_score'] ?? 0;
        $recoveriesModuleScore = $data['recoveries_module_score'] ?? 0;
        $creditModuleScore = $data['credit_module_score'] ?? 0;
        $annualIncreaseModuleScore = $data['annual_increase_module_score'] ?? 0;

        $land_ctn = 0;
        $land_price = 0;
        //匹配需求-拿地
        foreach ($landDataArr as $item) {
            foreach ($item['land_usage_list'] as $landUsage) {
                // 用户订阅设置了【土地用途】：只匹配相同的【土地用途】的地块
                // 用户订阅没有设置【土地用途】：匹配所有的地块
                if (in_array($landUsage['name'], $subscriptionLandUsageList) || count($subscriptionLandUsageList) == 0) {
                    $land_ctn += 1;
                    $land_price += $item['price'];
                    break;
                }
            }
        }


        $project_ctn = 0;
        $project_price = 0;
        //匹配需求-在建项目
        foreach ($projectDataArr as $item) {
            // 用户订阅设置了【在建类型】：只匹配相同的【在建类型】的项目
            // 用户订阅没有设置【在建类型】：匹配所有的项目
            if (in_array($item['prj_type'], $subscriptionProjectTypeList) || count($subscriptionProjectTypeList) == 0) {
                $project_ctn += 1;
                $project_price += $item['price'];
            }
        }

        // 匹配需求-拿地数量得分
        $land_ctn_score = $land_ctn * 5 < 30 ? $land_ctn * 5 : 30;
        // 匹配需求-拿地金额得分
        $land_price_score = floor($land_price / 1000) < 30 ? floor($land_price / 1000) : 30;
        // 匹配需求-在建项目数量得分
        $project_ctn_score = $project_ctn * 5 < 30 ? $project_ctn * 5 : 30;
        // 匹配需求-在建项目投资得分
        $project_price_score = floor($project_price / 1000) < 30 ? floor($project_price / 1000) : 30;
        // 匹配需求模块得分
        $matchRequirementModuleScore = ($land_ctn_score + $land_price_score + $project_ctn_score + $project_price_score) * 0.3;
        // 开发商总得分（得分区间为0-100分，大于100按100分计算）
        $developer_score = $investModuleScore + $recoveriesModuleScore + $creditModuleScore + $annualIncreaseModuleScore + $matchRequirementModuleScore;
        if ($developer_score > 100) {
            $developer_score = 100;
        }
        if ($developer_score < 0) {
            $developer_score = 0;
        }

        return [
            "developer_score" => round($developer_score, 2),
            "match_requirement_module_score" => round($matchRequirementModuleScore, 2),
            "match_requirement_land_ctn" => $land_ctn,
            "match_requirement_project_ctn" => $project_ctn,
            // todo:此信息临时返回，用于测试方便校验数据，上生产环境需要删除
            /*
            "tmp_data" => [
                 "match_requirement_land_ctn" => $land_ctn,
                 "match_requirement_land_ctn_score" => $land_ctn_score,
                 "match_requirement_land_price" => $land_price,
                 "match_requirement_land_price_score" => $land_price_score,
                 "match_requirement_project_ctn" => $project_ctn,
                 "match_requirement_project_ctn_score" => $project_ctn_score,
                 "match_requirement_project_price" => $project_price,
                 "match_requirement_project_price_score" => $project_price_score,
                 "investModuleScore" => $investModuleScore,
                 "recoveriesModuleScore" => $recoveriesModuleScore,
                 "creditModuleScore" => $creditModuleScore,
                 "annualIncreaseModuleScore" => $annualIncreaseModuleScore,
                 "matchRequirementModuleScore" => $matchRequirementModuleScore,
             ]
            */
        ];
    }


    private function constructCondition($keyword, $area = [], $province = [], $city = [], $companyType = [],
                                        $projectType = '', $landType = [], $tags = [], $companyLevel = [], $industryCategoryMiddle = [])
    {
        $query = [];
        if (!empty($keyword)) {
            $query['function_score']['query']['bool']['must'][] = [
                'match' => ['developer_name' => $keyword]
            ];
            $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ? \Yii::$app->params['CommonDataDeveloperSlop'] : 2;
            $query['function_score']['query']['bool']['should'][] = [
                'match_phrase' => ['developer_name' => ["query" => $keyword, "boost" => 100, 'slop' => $slop]]
            ];
            $query['function_score']['query']['bool']['should'][] = [
                'match_phrase' => ['name_traditional' => ["query" => $keyword, "boost" => 100]]
            ];
            $subWords = $this->getAnalyze($keyword);
            if (!empty($subWords)) {
                foreach ($subWords as $key => $val) {
                    $query['function_score']['query']['bool']['should'][] = [
                        'match_phrase' => ['developer_name' => ["query" => $val, "boost" => 50]]
                    ];
                }
            }
        }
        if (!empty($province)) {
            $query['function_score']['query']['bool']['must'][] = [
                'terms' => ['province_code.keyword' => $province]
            ];
        }
        if (!empty($city)) {
            $query['function_score']['query']['bool']['must'][] = [
                'terms' => ['city_code.keyword' => $city]
            ];
        }
        if (!empty($area)) {
            $query['function_score']['query']['bool']['must'][] = [
                'bool' => [
                    'should' => [
                        ['terms' => ['province_code.keyword' => $area]],
                        ['terms' => ['city_code.keyword' => $area]]
                    ]
                ]
            ];
        }
        //公司类型，项目类型
        if (!empty($companyType)) {
            $query['function_score']['query']['bool']['must'][] = [
                'terms' => ['company_type.keyword' => $companyType]
            ];
        }
        if (!empty($projectType)) {
            $nestedProjectTypeQuery['bool']['filter']['term']['project_type.project_type_label.keyword'] = $projectType;
            $query['function_score']['query']['bool']['must'][] = [
                'nested' => [
                    'path' => 'project_type',
                    'query' => $nestedProjectTypeQuery
                ]
            ];
        }
        if (is_array($landType) && count($landType) > 0) {
            $nestedLandUsageQuery['bool']['filter']['terms']['land_usage_type_label_arr.project_type_label.keyword'] = $landType;
            $query['function_score']['query']['bool']['must'][] = [
                'nested' => [
                    'path' => 'land_usage_type_label_arr',
                    'query' => $nestedLandUsageQuery
                ]
            ];
        }

        if (!empty($tags)) {
            $tagsCondition = [];
            foreach ($tags as $k => $v) {
                if ($v == "") continue;
                $tagsCondition[] = [
                    'term' => [$k . '.keyword' => $v]
                ];
            }
            if (!empty($tagsCondition)) {
                $query['function_score']['query']['bool']['must'][] = [
                    "bool" => [
                        "should" => $tagsCondition,
                    ]
                ];
            }
        }

        if (!empty($companyLevel)) {
            $companyLevelCondition = [];
            foreach ($companyLevel as $k => $v) {
                if ($v == "") continue;
                $companyLevelCondition[] = [
                    'term' => [$k . '.keyword' => $v]
                ];
            }
            if (!empty($companyLevelCondition)) {
                $query['function_score']['query']['bool']['must'][] = [
                    "bool" => [
                        "should" => $companyLevelCondition,
                    ]
                ];
            }
        }

        if (!empty($industryCategoryMiddle)) {
            $query['function_score']['query']['bool']['must'][] = [
                'terms' => ['industry_category_middle.keyword' => $industryCategoryMiddle]
            ];
        }

        //权重排序
        $query['function_score']['functions'] = [
            ['script_score' => ['script' => "doc['taken_land_area'].value>10?200:doc['taken_land_area'].value>5?150:doc['taken_land_area'].value>3?100:doc['taken_land_area'].value>1?50:0"]],
            ['script_score' => ['script' => "doc['open_project_num'].value>10?200:doc['open_project_num'].value>5?150:doc['open_project_num'].value>3?100:doc['open_project_num'].value>1?50:0"]],
//            ['script_score' => ['script' => "doc['cooperation_enterprise_num'].value>10?200:doc['cooperation_enterprise_num'].value>5?150:doc['cooperation_enterprise_num'].value>3?100:doc['cooperation_enterprise_num'].value>1?50:0"]],
//            ['script_score' => ['script' => "doc['purchase_demand_num'].value>10?200:doc['purchase_demand_num'].value>5?150:doc['purchase_demand_num'].value>3?100:doc['purchase_demand_num'].value>1?50:0"]]
        ];
        $query['function_score']['score_mode'] = 'sum';
        $query['function_score']['boost_mode'] = 'sum';

        return $query;
    }

    public function getRecommendedDeveloperList(
        $keyword = [], $areaCodes = [],
        $projectLabels = [], $landUsageLabels = [], $fitmentFeeLabels = [], $isPriceGtAvg = [],
        $startTime = '', $endTime = '',
        $page = 1, $pageSize = 10): array
    {
        $condition = $this->constructRecommendedDeveloperCondition($keyword, $areaCodes,
            $projectLabels, $landUsageLabels, $fitmentFeeLabels, $isPriceGtAvg, $startTime, $endTime);
        $query = BigDataRecommendedDeveloperModel::find()->query($condition);

        $query->orderBy(['is_new' => SORT_DESC, "_score" => SORT_DESC]);
        $total = $query->count();
        $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        $data = $query->asArray()->all();
        $result = ['total' => $total, 'list' => []];
        foreach ($data as $dv) {
            $tmp = $dv['_source'];

            $pickedProjects = [];
            $bestMatchProjects = [];
            //	把匹配成功的项目找出来展示，按时间倒序取2条,在省市雷达里用
            if (isset($tmp["land_info"]) && is_array($tmp["land_info"])) {
                foreach ($tmp["land_info"] as &$item) {
                    $item["type"] = "land";
                    $pickedProjects[] = $item;

                    if ($this->isMatch($item, $keyword, $landUsageLabels, $startTime, $areaCodes, "land")) {
                        $bestMatchProjects[] = $item;
                    }
                }
            }
            if (isset($tmp["build_project_info"]) && is_array($tmp["build_project_info"])) {
                foreach ($tmp["build_project_info"] as &$item) {
                    $item["type"] = "project";
                    $pickedProjects[] = $item;
                    if ($this->isMatch($item, $keyword, $projectLabels, $startTime, $areaCodes, "project")) {
                        $bestMatchProjects[] = $item;
                    }
                }
            }
            if (isset($tmp["trading_project_info"]) && is_array($tmp["trading_project_info"])) {
                foreach ($tmp["trading_project_info"] as &$item) {
                    $item["type"] = "trading";
                    $pickedProjects[] = $item;
                    if ($this->isMatch($item, $keyword, $fitmentFeeLabels, $startTime, $areaCodes, "trading")) {
                        $bestMatchProjects[] = $item;
                    }
                }
            }

            // 按时间倒序排序
            if (sizeof($bestMatchProjects) > 0) {
                $date = array_column($bestMatchProjects, "date");
                array_multisort($date, SORT_DESC, $bestMatchProjects);
                $tmp["picked_projects"] = json_encode(array_slice($bestMatchProjects, 0, 2), 256);
            } else {
                $date = array_column($pickedProjects, "date");
                array_multisort($date, SORT_DESC, $pickedProjects);
                $tmp["picked_projects"] = json_encode(array_slice($pickedProjects, 0, 2), 256);
            }
            $result['list'][] = $tmp;
        }
        return $result;
    }

    private function isMatch($project, $keywords, $labels, $startTime, $areaCodes, $type): bool
    {
        if (!isset($project["title"]) || !isset($project["date"])) {
            return false;
        }
        $matchKeyword = false;
        $matchLabel = false;
        $matchTime = false;
        $matchArea = false;
        foreach ($keywords as $keyword) {
            if (strstr($project["title"], $keyword)) {
                $matchKeyword = true;
                break;
            }
        }
        if (strtotime($startTime) <= strtotime($project["date"])) {
            $matchTime = true;
        }

        if (empty($labels)) {
            $matchLabel = true;
        } else {
            switch ($type) {
                case "land":
                    if (isset($project["land_usage_type_label_arr"])) {
                        if (sizeof(array_intersect($labels, $project["land_usage_type_label_arr"])) > 0) {
                            $matchLabel = true;
                        }
                    }
                    break;
                case "project":
                    if (isset($project["project_label"])) {
                        if (in_array($project["project_label"], $labels)) {
                            $matchLabel = true;
                        }
                    }
                    break;
                case "trading":
                    if (isset($project["fitment_fee_label"])) {
                        if (in_array($project["project_label"], $labels)) {
                            $matchLabel = true;
                        }
                    }
                    break;
            }
        }

        if (isset($project["province_code"]) && in_array($project["province_code"], $areaCodes)) {
            $matchArea = true;
        }
        if (isset($project["city_code"]) && in_array($project["city_code"], $areaCodes)) {
            $matchArea = true;
        }

        return $matchKeyword && $matchLabel && $matchTime && $matchArea;
    }

    private function constructRecommendedDeveloperCondition(
        $keywords = [], $areaCodes = [],
        $projectLabels = [], $landUsageLabels = [],
        $fitmentFeeLabels = [], $isPriceGtAvg = [], $startTime = '', $endTime = ''): array
    {
        //( 近一年有拿地 and 项目的省市地区匹配成功 and ((未设置订阅土地类型) or (设置了土地类型且有匹配上的)) and 土地标题匹配项目关键词  and 是否高端项目)
        //	or ( 近一年有在建 and 项目的省市地区匹配成功 and ((未设置在建类型) or (设置了在建类型且有匹配上的)) and 在建标题匹配关键词  and 是否高端项目)
        //	or ( 近一年有在售 and ((未设置在售类型) or (设置了在售类型且有匹配上的)) and 在售标题匹配关键词)  and 是否高端项目)
        //
        //{
        //  "query": {
        //    "bool": {
        //      "should": [
        //        {
        //          "bool": {
        //            "must": [
        //              {
        //                 近一年有拿地 and 项目的省市地区匹配成功 and ((未设置订阅土地类型) or (设置了土地类型且有匹配上的)) and 土地标题匹配项目关键词  and 是否高端项目
        //              }
        //            ]
        //          }
        //        },{
        //          "bool": {
        //            "must": [
        //              {
        //                近一年有在建 and 项目的省市地区匹配成功 and ((未设置在建类型) or (设置了在建类型且有匹配上的)) and 在建标题匹配关键词  and 是否高端项目
        //              }
        //            ]
        //          }
        //
        //        },{
        //          "bool": {
        //            "must": [
        //              {
        //                近一年有在售 and ((未设置在售类型) or (设置了在售类型且有匹配上的)) and 在售标题匹配关键词)  and 是否高端项目
        //              }
        //            ]
        //          }
        //        }
        //      ]
        //    }
        //  }
        //}
        $slop = !empty(\Yii::$app->params['CommonDataDeveloperSlop']) ? \Yii::$app->params['CommonDataDeveloperSlop'] : 2;

        $landInfoCondition = [];
        $landCondition = ["bool" => [
            "must" => [
                [
                    "term" => [
                        "has_land_info" => 1
                    ]
                ],
                [
                    "nested" => [
                        "path" => "land_info",
                        "query" => [
                            "bool" => [
                                "must" => &$landInfoCondition
                            ]
                        ]
                    ]
                ]
            ]
        ]];

        //时间区间内有拿地 and 项目的省市地区匹配成功 and ((未设置订阅土地类型) or (设置了土地类型且有匹配上的)) and 土地标题匹配项目关键词  and 是否高端项目

        //关键词匹配
        if (!empty($keywords)) {
            $keywordCondition = [];
            foreach ($keywords as $k) {
                $keywordCondition[] = [
                    'match_phrase' => ['land_info.title' => ["query" => $k, "boost" => 10, 'slop' => $slop]]
                ];
            }
            $landInfoCondition[] = ["bool" => ["should" => $keywordCondition]];
        }

        // 时间区间内
        if (!empty($startTime) && !empty($endTime)) {
            $timeCondition = [
                "range" => [
                    "land_info.date" => [
                        "from" => $startTime,
                        "to" => $endTime
                    ]
                ]
            ];
            $landInfoCondition[] = $timeCondition;
        }

        // 省市地区匹配
        if (!empty($areaCodes)) {
            $areaCondition = [
                "bool" => [
                    "should" => [
                        [
                            "terms" => [
                                "land_info.province_code" => $areaCodes
                            ]
                        ], [
                            "terms" => [
                                "land_info.city_code" => $areaCodes
                            ]
                        ]
                    ]
                ]
            ];
            $landInfoCondition[] = $areaCondition;
        }

        //高端项目匹配
        if (!empty($isPriceGtAvg)) {
            $landInfoCondition[] = [
                "terms" => ["land_info.is_price_gt_avg" => $isPriceGtAvg]
            ];
        }

        if (!empty($landUsageLabels)) {
            $landInfoCondition[] = [
                "nested" => [
                    "path" => "land_info.land_usage_type_label_arr",
                    "query" => [
                        "terms" => ["land_info.land_usage_type_label_arr.name" => $landUsageLabels]
                    ]
                ]
            ];
        }

        //近一年有在建 and 项目的省市地区匹配成功 and ((未设置在建类型) or (设置了在建类型且有匹配上的)) and 在建标题匹配关键词  and 是否高端项目
        $buildProjectInfoCondition = [];
        $buildProjectCondition = ["bool" => [
            "must" => [
                [
                    "term" => [
                        "has_build_project" => 1
                    ]
                ],
                [
                    "nested" => [
                        "path" => "build_project_info",
                        "query" => [
                            "bool" => [
                                "must" => &$buildProjectInfoCondition
                            ]
                        ]
                    ]
                ]
            ]
        ]];

        //关键词匹配
        if (!empty($keywords)) {
            $keywordCondition = [];
            foreach ($keywords as $k) {
                $keywordCondition[] = [
                    'match_phrase' => ['build_project_info.title' => ["query" => $k, "boost" => 10, 'slop' => $slop]]
                ];
            }
            $buildProjectInfoCondition[] = ["bool" => ["should" => $keywordCondition]];
        }

        // 时间区间内
        if (!empty($startTime) && !empty($endTime)) {
            $timeCondition = [
                "range" => [
                    "build_project_info.date" => [
                        "from" => $startTime,
                        "to" => $endTime
                    ]
                ]
            ];
            $buildProjectInfoCondition[] = $timeCondition;
        }

        // 省市地区匹配
        if (!empty($areaCodes)) {
            $areaCondition = [
                "bool" => [
                    "should" => [
                        [
                            "terms" => [
                                "build_project_info.province_code" => $areaCodes
                            ]
                        ], [
                            "terms" => [
                                "build_project_info.city_code" => $areaCodes
                            ]
                        ]
                    ]
                ]
            ];
            $buildProjectInfoCondition[] = $areaCondition;
        }

        //高端项目匹配
        if (!empty($isPriceGtAvg)) {
            $buildProjectInfoCondition[] = [
                "terms" => ["build_project_info.is_price_gt_avg" => $isPriceGtAvg]
            ];
        }

        if (!empty($projectLabels)) {
            $buildProjectInfoCondition[] = [
                "terms" => ["build_project_info.project_label" => $projectLabels]
            ];
        }

        $tradingProjectInfoCondition = [];
        $tradingProjectCondition = ["bool" => [
            "must" => [
                [
                    "term" => [
                        "has_trading_project" => 1
                    ]
                ],
                [
                    "nested" => [
                        "path" => "trading_project_info",
                        "query" => [
                            "bool" => [
                                "must" => &$tradingProjectInfoCondition
                            ]
                        ]
                    ]
                ]
            ]
        ]];

        //关键词匹配
        if (!empty($keywords)) {
            $keywordCondition = [];
            foreach ($keywords as $k) {
                $keywordCondition[] = [
                    'match_phrase' => ['trading_project_info.title' => ["query" => $k, "boost" => 10, 'slop' => $slop]]
                ];
            }
            $tradingProjectInfoCondition[] = ["bool" => ["should" => $keywordCondition]];
        }

        // 时间区间内
        if (!empty($startTime) && !empty($endTime)) {
            $timeCondition = [
                "range" => [
                    "trading_project_info.date" => [
                        "from" => $startTime,
                        "to" => $endTime
                    ]
                ]
            ];
            $tradingProjectInfoCondition[] = $timeCondition;
        }

        // 省市地区匹配
        if (!empty($areaCodes)) {
            $areaCondition = [
                "bool" => [
                    "should" => [
                        [
                            "terms" => [
                                "trading_project_info.province_code" => $areaCodes
                            ]
                        ], [
                            "terms" => [
                                "trading_project_info.city_code" => $areaCodes
                            ]
                        ]
                    ]
                ]
            ];
            $tradingProjectInfoCondition[] = $areaCondition;
        }

        //高端项目匹配
        if (!empty($isPriceGtAvg)) {
            $tradingProjectInfoCondition[] = [
                "terms" => ["trading_project_info.is_price_gt_avg" => $isPriceGtAvg]
            ];
        }

        if (!empty($fitmentFeeLabels)) {
            $tradingProjectInfoCondition[] = [
                "terms" => ["trading_project_info.fitment_fee_label" => $fitmentFeeLabels]
            ];
        }


        $query['function_score']['query']['bool']['should'] = [$landCondition, $buildProjectCondition, $tradingProjectCondition];
//        echo json_encode($query, 256);
//        exit;
        return $query;
    }

    public function getDeveloperScore($organizingCodes = [], $subscription = []): array
    {
        //通过社会信用代码取查询采购商主档案
        $condition = ["function_score" => ["query" => ['terms' => ['organizing_code.keyword' => $organizingCodes]]]];
        $query = BigDataDeveloperModel::find()
            ->query($condition);
        $query->limit(count($organizingCodes));
        $data = $query->asArray()->all();

        $result = [];
        foreach ($data as $dv) {
            $tmp = $dv['_source'];
            $developerScoreInfo = $this->getDeveloperScoreInfo($tmp, $subscription);
            $tmp['developer_score'] = $developerScoreInfo['developer_score'] ? intval($developerScoreInfo['developer_score']) : 0;
            $tmp['match_requirement_module_score'] = $developerScoreInfo['match_requirement_module_score'] ? intval($developerScoreInfo['match_requirement_module_score']) : 0;
            $tmp['match_requirement_land_ctn'] = $developerScoreInfo['match_requirement_land_ctn'] ?? 0;
            $tmp['match_requirement_project_ctn'] = $developerScoreInfo['match_requirement_project_ctn'] ?? 0;
            $result[] = $tmp;
        }
        return $result;
    }

    public function formatDeveloper($data)
    {
        //1、显示赋值：因为 es 的值如果为 null 会没有字段
        $return_params = [
            'organizing_code' => 'string',
            'number_of_employees' => 'string',
            'taken_land_area' => 'string',
            'open_project_num' => 'string',
            'purchase_demand_num' => 'string',
            'cooperation_enterprise_num' => 'string',
            'developer_name' => 'string',
            'short_name' => 'string',
            'developer_logo' => 'string',
            'developer_id' => 'string',
            'legal_name' => 'string',
            'regist_capi' => 'string',
            'rec_capi' => 'string',
            'establish_date' => 'string',
            'term_start' => 'string',
            'term_end' => 'string',
            'status' => 'string',
            'enterprise_nature' => 'string',
            'scope' => 'string',
            'province' => 'string',
            'city' => 'string',
            'province_code' => 'string',
            'city_code' => 'string',
            'address' => 'string',
            'company_type' => 'string',
            'business_status_label' => 'string',
            'listed_enterprises_label' => 'string',
            'top_developer_name' => 'string',
            'top_organizing_code' => 'string',
            'top_company_type' => 'string',
            'top_company_type_label' => 'string',
            'purchase_contact_cnt' => 'string',
            'commence_permit_cnt' => 'string',
            'commence_permit_cnt_1year' => 'string',
            'developer_top_100_label' => 'string',
            'high_project_customers_label' => 'string',
            'developer_activity_label' => 'string',
            'is_ycg_certification' => 'string',
            'is_ycg_offline_business_connect' => 'string',
            'is_new_area_expand_label' => 'string',
            'is_new_land_usage_expand_label' => 'string',
            'is_new_decorate_expand_label' => 'string',
            'industry_category' => 'string',
            'industry_category_big' => 'string',
            'industry_category_middle' => 'string',
            'industry_category_small' => 'string',
            'new_house_sale_2year' => 'string',
            'name_traditional' => 'string',
            'invest_module_score' => 'string',
            'recoveries_module_score' => 'string',
            'credit_module_score' => 'string',
            'annual_increase_module_score' => 'string',
            'take_land_cnt_2year' => 'string',
            'sell_project_cnt_2year' => 'string',
            'purchase_demand_cnt_2year' => 'string',
            'cooperation_enterprise_cnt_2year' => 'string',
            'commence_permit_cnt_2year' => 'string',
        ];

        foreach ($return_params as $rk => $rv) {
            $tmp = isset($data[$rk]) ? $data[$rk] : '';
            $tmp = $tmp === '1990-01-01 00:00:00' ? '' : $tmp;
            if ($rv == 'int') {
                $data[$rk] = (int)$tmp;
            } elseif ($rv == 'array') {
                $data[$rk] = empty($tmp) ? [] : $tmp;
            } else {
                $data[$rk] = $tmp;
            }

        }

        return $data;
    }
}